package com.cykj.management.activity;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cykj.management.R;
import com.cykj.management.common.MyLog;
import com.cykj.management.speech.util.FucUtil;
import com.cykj.management.speech.util.JsonParser;
import com.cykj.management.speech.util.XmlParser;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.GrammarListener;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.LexiconListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.util.ResourceUtil;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.BasicMessageChannel;

import android.content.Context;

/**
 * @author haojie
 * 离线命令词识别
 */
public class AsrActivity extends BaseActivity implements OnClickListener, BasicMessageChannel.MessageHandler {
    public static final String TAG = AsrActivity.class.getSimpleName();

    private Toast mToast;

    /**
     * 语音识别对象
     */
    private SpeechRecognizer mAsr;

    /**
     * 缓存
     */
    private SharedPreferences mSharedPreferences;

    /**
     * 本地语法文件
     */
    private String mLocalGrammar = null;

    /**
     * 本地词典
     */
    private String mLocalLexicon = null;

    /**
     * 本地语法构建路径
     */
//    private String grmPath = Environment.getExternalStorageDirectory()
//            .getAbsolutePath() + "/msc/test";
//    /data/user/0/com.cykj.management/databases/management.db'.
    private String grmPath = "/data/user/0/com.cykj.management/msc/test";
    /**
     * 返回结果格式，支持：xml,json
     */
    private String mResultType = "json";

    private final String KEY_GRAMMAR_ABNF_ID = "grammar_abnf_id";
    private final String GRAMMAR_TYPE_ABNF = "abnf";
    private final String GRAMMAR_TYPE_BNF = "bnf";

    private String mEngineType = "local";

    private String data;

    private Context mContext;
    private BasicMessageChannel mscChannel;
    private static AsrActivity instance;


    public AsrActivity() {
    }

    public static AsrActivity getInstance() {
        if (instance == null) {
            instance = new AsrActivity();
        }
        return instance;
    }

    public void init(Context context, String data, BasicMessageChannel mscChannel) {
        this.mContext = context;

        this.mscChannel = mscChannel;
        // 初始化识别对象
        this.mAsr = SpeechRecognizer.createRecognizer(context, mInitListener);
        mLocalGrammar = FucUtil.readFile(context, "asr/gate.bnf", "utf-8");
        mSharedPreferences = context.getSharedPreferences(context.getPackageName(), MODE_PRIVATE);
        mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        buildGrammar(context);
        this.data = data;
//        HashMap<Object, Object> map = new HashMap<>();
//        map.put("receiveGate", true);
//        map.put("message", TAG + "： 接收到闸门的数据了");
//        mscChannel.send(map);
        MyLog.d(TAG, "init " + data);
        updateISRLexcion(data);

        if (mAsr == null) {
            MyLog.e(TAG, "masr is null");
        }
    }

    public void startRecognize() {
        if (this.mAsr == null) {
            MyLog.e(TAG, "mAsr 为 null");
            return;
        }
        if (!setParam()) {
            showTip("请先构建语法。");
            return;
        }
        MyLog.w(TAG, "data: " + data);
//        updateISRLexcion(data);
        ret = this.mAsr.startListening(mRecognizerListener);

        if (ret != ErrorCode.SUCCESS) {
            showTip("识别失败,错误码: " + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
        } else {

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLog.d(TAG, "onCreate");
        setContentView(R.layout.activity_asr);
        initLayout();
        // 初始化识别对象
        this.mAsr = SpeechRecognizer.createRecognizer(this, mInitListener);
        mLocalGrammar = FucUtil.readFile(this, "asr/gate.bnf", "utf-8");
        mSharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);

        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        buildGrammar(this.getApplicationContext());
        this.data = getIntent().getStringExtra("data");
        mscChannel.send(TAG + "： 接收到intent的数据了");

        if (mAsr == null) {
            MyLog.e(TAG, "masr is null");
        }

        //更新从flutter端传来的数据
        if (data != null) {
            updateISRLexcion(data);
        }

        // 初始化语法、命令词
//        mLocalLexicon = "通道\n闸门\n北门\n";

    }

    private void initLayout() {
        findViewById(R.id.isr_grammar).setOnClickListener(this);
        findViewById(R.id.isr_lexcion).setOnClickListener(this);
        findViewById(R.id.isr_recognize).setOnClickListener(this);
        findViewById(R.id.isr_stop).setOnClickListener(this);
        findViewById(R.id.isr_cancel).setOnClickListener(this);
    }

    // 函数调用返回值
    int ret = 0;


    @Override
    public void onClick(View v) {
        if (null == mAsr) {
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            showTip("创建对象失败，请确认 libmsc.so 放置正确，\n 且有调用 createUtility 进行初始化");
            return;
        }
        if (null == mEngineType) {
            showTip("请先选择识别引擎类型");
            return;
        }
        switch (v.getId()) {
            case R.id.isr_grammar:
                showTip("上传预设关键词/语法文件");
                buildGrammar(this.getApplicationContext());
                break;
            case R.id.isr_recognize:
                ((EditText) findViewById(R.id.isr_text)).setText(null);// 清空显示内容
                if (!setParam()) {
                    showTip("请先构建语法。");
                    return;
                }
                ret = mAsr.startListening(mRecognizerListener);

                if (ret != ErrorCode.SUCCESS) {
                    showTip("识别失败,错误码: " + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
                } else {

                }
                break;
            case R.id.isr_lexcion: //更新词典
                mLocalLexicon = data;
                ((EditText) findViewById(R.id.isr_text)).setText(mLocalLexicon);
                mAsr.setParameter(SpeechConstant.PARAMS, null);
                // 设置引擎类型
                mAsr.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
                // 设置资源路径
                mAsr.setParameter(ResourceUtil.ASR_RES_PATH, getResourcePath());
                //使用8k音频的时候请解开注释
//				mAsr.setParameter(SpeechConstant.SAMPLE_RATE, "8000");
                // 设置语法构建路径
                mAsr.setParameter(ResourceUtil.GRM_BUILD_PATH, grmPath);
                // 设置语法名称
                mAsr.setParameter(SpeechConstant.GRAMMAR_LIST, "gate");
                // 设置文本编码格式
                mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
                ret = mAsr.updateLexicon("passage", mLocalLexicon, lexiconListener);
                if (ret != ErrorCode.SUCCESS) {
                    showTip("更新词典失败,错误码：" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
                }
                break;
            // 停止识别
            case R.id.isr_stop:
                mAsr.stopListening();
                showTip("停止识别");
                break;
            // 取消识别
            case R.id.isr_cancel:
                mAsr.cancel();
                showTip("取消识别");
                TtsActivity.getInstance().tts_play("正在为您开启");
                break;
            default:
                break;
        }
    }

    private void buildGrammar(Context context) {
        if (mEngineType.equals(SpeechConstant.TYPE_LOCAL)) {

            mAsr.setParameter(SpeechConstant.PARAMS, null);
            // 设置文本编码格式
            mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
            // 设置引擎类型
            mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
            // 设置语法构建路径
            mAsr.setParameter(ResourceUtil.GRM_BUILD_PATH, grmPath);

            // 设置资源路径
            mAsr.setParameter(ResourceUtil.ASR_RES_PATH, getResourcePath());
//                    ret = mAsr.updateLexicon("contact", mContent, lexiconListener);
            ret = mAsr.buildGrammar(GRAMMAR_TYPE_BNF, mLocalGrammar, grammarListener);
            if (ret != ErrorCode.SUCCESS) {
                showTip("语法构建失败,错误码：" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
            }
        }
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            MyLog.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败,错误码：" + code);
            }
        }
    };

    /**
     * 更新词典监听器。
     */
    private LexiconListener lexiconListener = new LexiconListener() {
        @Override
        public void onLexiconUpdated(String lexiconId, SpeechError error) {
            if (error == null) {
//                showTip("词典更新成功");
                MyLog.i(TAG, "词典更新成功");
            } else {
//                showTip("词典更新失败,错误码：" + error.getErrorCode());
                MyLog.e(TAG, "词典更新失败,错误码：" + +error.getErrorCode());
            }
        }
    };

    /**
     * 构建语法监听器。
     */
    private GrammarListener grammarListener = new GrammarListener() {
        @Override
        public void onBuildFinish(String grammarId, SpeechError error) {
            if (error == null) {
                if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    if (!TextUtils.isEmpty(grammarId))
                        editor.putString(KEY_GRAMMAR_ABNF_ID, grammarId);
                    editor.commit();
                }
//                showTip("语法构建成功：" + grammarId);
                MyLog.i(TAG, "语法构建成功：" + grammarId);
            } else {
//                showTip("语法构建失败,错误码：" + error.getErrorCode());
                MyLog.e(TAG, "语法构建失败,错误码：" + error.getErrorCode());
            }
        }
    };

    /**
     * 识别监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            showTip("当前正在说话，音量大小：" + volume);
//            MyLog.d(TAG, "返回音频数据：" + data.length);
        }

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            showTip("开始说话");
            MyLog.i(TAG, "开始说话");
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            showTip("结束说话");
            MyLog.i(TAG, "结束说话");
        }

        @Override
        public void onResult(RecognizerResult result, boolean isLast) {
            if (null != result && !TextUtils.isEmpty(result.getResultString())) {
//                MyLog.d(TAG, "recognizer result：" + result.getResultString());
                String text = "";
                if (mResultType.equals("json")) {
                    text = JsonParser.parseGrammarResult(result.getResultString(), mEngineType);
                } else if (mResultType.equals("xml")) {
                    text = XmlParser.parseNluResult(result.getResultString());
                } else {
                    text = result.getResultString();
                }

                Map<String, Object> map = new HashMap<>();
                //text 的内容 e.g.【结果】开启闸门【置信度】61
                MyLog.d(TAG, "recognizer result：" + text);
                map.put("recognizerResult", text);
                AsrActivity.getInstance().mscChannel.send(map);

            } else {
                MyLog.w(TAG, "recognizer result : null");
                TtsActivity.getInstance().tts_play("没有识别到语音");
            }
        }

        @Override
        public void onError(SpeechError speechError) {
            int errorCode = speechError.getErrorCode();
            showTip("onError Code：" + errorCode);
            MyLog.e(TAG, "onError Code：" + errorCode);
            TtsActivity ttsActivity = TtsActivity.getInstance();
            ttsActivity.init(AsrActivity.getInstance().mContext);

            switch (errorCode) { //https://www.xfyun.cn/document/error-code?code=20005
                case 10114:
                    ttsActivity.tts_play("会话超时"); //The boundless forest sheds its leaves shower by shower
                    break;
                case 20005:
                    ttsActivity.tts_play("没有匹配的结果");
                    break;
                    //23127 语法未更新
            }
            WeakActivity.getInstance().startListening();

        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle bundle) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void showTip(String str) {
        mToast.setText(str);
        mToast.show();
    }

    /**
     * 参数设置
     *
     * @return
     */
    public boolean setParam() {
        boolean result = false;
        // 清空参数
        mAsr.setParameter(SpeechConstant.PARAMS, null);
        // 设置识别引擎
        mAsr.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        if ("cloud".equalsIgnoreCase(mEngineType)) {
            String grammarId = mSharedPreferences.getString(KEY_GRAMMAR_ABNF_ID, null);
            if (TextUtils.isEmpty(grammarId)) {
                result = false;
            } else {
                // 设置返回结果格式
                mAsr.setParameter(SpeechConstant.RESULT_TYPE, mResultType);
                // 设置云端识别使用的语法id
                mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
                result = true;
            }
        } else {
            // 设置本地识别资源
            mAsr.setParameter(ResourceUtil.ASR_RES_PATH, getResourcePath());
            // 设置语法构建路径
            mAsr.setParameter(ResourceUtil.GRM_BUILD_PATH, grmPath);
            // 设置返回结果格式
            mAsr.setParameter(SpeechConstant.RESULT_TYPE, mResultType);
            // 设置本地识别使用语法id
            mAsr.setParameter(SpeechConstant.LOCAL_GRAMMAR, "gate");
            // 设置识别的门限值
            mAsr.setParameter(SpeechConstant.ASR_THRESHOLD, "50");
            // 使用8k音频的时候请解开注释
//			mAsr.setParameter(SpeechConstant.SAMPLE_RATE, "8000");
            result = true;
        }

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
//        mAsr.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
//        mAsr.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/asr.wav");
        return result;
    }


    //获取识别资源路径
    private String getResourcePath() {
        StringBuffer tempBuffer = new StringBuffer();
        //识别通用资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this.mContext, ResourceUtil.RESOURCE_TYPE.assets, "asr/common.jet"));
        return tempBuffer.toString();
    }

    /**
     * 更新语法词典
     */
    void updateISRLexcion(String data) {
        mLocalLexicon = data;
        mAsr.setParameter(SpeechConstant.PARAMS, null);
        // 设置引擎类型
        mAsr.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
        // 设置资源路径
        mAsr.setParameter(ResourceUtil.ASR_RES_PATH, getResourcePath());
        //使用8k音频的时候请解开注释
//				mAsr.setParameter(SpeechConstant.SAMPLE_RATE, "8000");
        // 设置语法构建路径
        mAsr.setParameter(ResourceUtil.GRM_BUILD_PATH, grmPath);
        // 设置语法名称
        mAsr.setParameter(SpeechConstant.GRAMMAR_LIST, "gate");
        // 设置文本编码格式
        mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
        ret = mAsr.updateLexicon("passage", mLocalLexicon, lexiconListener);
        if (ret != ErrorCode.SUCCESS) {
            showTip("更新词典失败,错误码：" + ret + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
        }
    }


    @Override
    public void onMessage(@Nullable final Object message, @NonNull final BasicMessageChannel.Reply reply) {
        MyLog.i(TAG, "onMessage: " + (message != null ? message.toString() : null));

        reply.reply("收到了消息了");
        mscChannel.send("123");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mAsr) {
            // 退出时释放连接
            mAsr.cancel();
            mAsr.destroy();
        }
    }


    public void release() {
        if (null != mAsr) {
            // 退出时释放连接
            mAsr.cancel();
            mAsr.destroy();
        }
        mAsr = null;
        instance = null;
    }

}